<template>
  <div v-loading="loading" class="app-container">
    <!-- 新增文章 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>新增文章</span>
      </div>
      <div>
        <el-row>
           <el-form :model="ruleForm" 
           :rules="rules" 
           ref="ruleForm" label-width="120px">
            <el-col :span="10">
                <el-form-item label="作者" prop="name">
                    <el-input placeholder="作者姓名" v-model="ruleForm.author"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="10">
                <el-form-item label="标题" prop="title">
                    <el-input placeholder="文章标题" v-model="ruleForm.title"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="是否显示" prop="delivery">
                    <el-switch v-model="ruleForm.isShow" :active-value="1" :inactive-value="0"></el-switch>
                </el-form-item>
            </el-col>
            <el-col :span="20">
                <el-form-item label="摘要" prop="desc">
                    <el-input placeholder="摘要" type="textarea" v-model="ruleForm.summary"/>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="封面图片">
                    <el-upload class="upload-demo" 
                        ref="upLoadPhoto"
                        :action="uploadUrl"
                        multiple
                        :headers="uploadHeaders"
                        :on-success="handleAvatarSuccess"
                        >
                            <el-button size="mini" type="primary">点击上传素材</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                    <img style="width:100px;height:auto;" v-if="ruleForm.coverImg" :src="ruleForm.coverImg" alt="">
                </el-form-item>
            </el-col>

            <el-col :span="24">
                <el-form-item  label="切换富文本类型" prop="desc">
                    <el-radio-group v-model="ruleForm.editorType">
                        <el-radio :label="0">富文本</el-radio>
                        <el-radio :label="1">markdown</el-radio>
                    </el-radio-group>
                      <span  style="margin-left: 40px; color: #e6a23c">
                          <i class="el-icon-warning"></i>注意!切换编辑器会清空编辑内容</span>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-upload
                v-show="ruleForm.editorType===0"
                class="upload-demo"
                :action="uploadUrl"
                ref="innerUpload"
                multiple
                :headers="uploadHeaders"
                :on-success="AvatarSuccess">
                <el-button size="small" type="primary">插入图片↓</el-button>
              </el-upload>
            </el-col>
            <el-col v-show="ruleForm.editorType===0">               
                 <Tinymce ref="ti" />           
            </el-col>
            <el-col v-show="ruleForm.editorType===1">
              <MdEditor ref="md" />
            </el-col>
            <el-col >
                <el-form-item>
                    <el-button style="margin:10px auto" size="mini" type="primary" @click="submitForm('ruleForm')">{{id?'立即修改':'立即新增'}}</el-button>
                </el-form-item>
            </el-col>
           </el-form>
        </el-row>
      </div>
    </el-card>
  </div>
</template>
<script>
import Tinymce from "@/components/Tinymce/index"
import MdEditor from "@/components/MarkdownEditor"
import mix from "@/mixin/index";
import product from "@/api/content/product";
export default {
    name:"AddArticle",//引入mixin用来上传文件
    mixins:[mix],
    components:{
      Tinymce,  //富文本
      MdEditor  //markdown
    },
  data() {
    return {
        loading:false,
        //新增文章列表
        ruleForm:{
          author:'',
          title:'',
          isShow:0,
          summary:'',
          coverImg:'',
          editorType:0,
          content1: '', // 富文本原文
          content2: '' // 富文本html
        },
        id:'',   //利用id查看是新增还是编辑
        //验证规则
        rules: {
          author: [
            { required: true, message: '请输入作者名字', trigger: 'blur' }
          ],
          title: [
            { required: true, message: '请输入文章标题', trigger: 'blur' }
          ],
          },


    };
  },
  methods:{
    //查找文章明细
    getproductArticle(){
      this.loading=true;
      product.productArticle(this.id).then(res=>{
        console.log(res);
        
        if(res.success){
          this.ruleForm=res.data.productArticle;
          //是否展示转换为1或0;
          this.ruleForm.isShow=this.formName.isShow?1:0;
          //渲染富文本框和md的内容
          this.$nextTick(()=>{
            if(this.ruleForm.editorType===0){
              this.setTi(this.ruleForm.content1)
            }else{
              this.setMd(this.ruleForm.content2)
            }
          })
        }else{
          this.$message.error("获取文章失败了")
        }
        this.loading=false;
      })
    },
      //新增按钮
      submitForm(formName){
        if(this.ruleForm.editorType===0){
          this.ruleForm.content1=this.ruleForm.content2=this.getTi()
        }else{
          this.ruleForm.content1=this.getMd().val;
          this.ruleForm.content2=this.getMd().html;
        }
        if(!this.ruleForm.content1||!this.ruleForm.content2){
          this.$message.warning("文章内容不能为空")
          return false
        }
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
             if(!this.id){
               //添加文章
               product.addArticle({...this.ruleForm}).then(res=>{
                 console.log(res);
                 if(res.success){
                   this.$router.push({name:"ArticleList"})
                 }else{
                   this.$message.error("添加文章失败")
                 }
               })
             }else{
               //更新文章
               product.updateArticle({...this.ruleForm}).then(res=>{
                 console.log(res);
                 if(res.success){
                   this.$router.push({name:"ArticleList"})
                 }else{
                   this.$message.error("更新文章失败了")
                 }
               })
             }

          } else {
            this.$message.error("不要忘记你还有必要内容没有填写哦")
            return false;
          }
        });
      },
      // //图片上传成功的回调方法
      handleAvatarSuccess(res,file){
          console.log(res,file)
        if(res.success){
          //清除显示的文件
          this.$refs.upLoadPhoto.clearFiles();
          this.ruleForm.coverImg=res.data.fileUrl;
        }else{
          this.$message.error("哎呀,这是图片上传失败喽")
        }

      },
      //插入图片上传成功之后的回调
      AvatarSuccess(res,file){
        console.log(res,file)
        if(res.success){
          //清除显示的文件
          this.$refs.innerUpload.clearFiles();
          this.$refs.ti.imageSuccessCBK(res.data.fileUrl);
        }else{
          this.$message.error("富文本图片上传失败了")
        }
      },
      //获取富文本框内容
      getTi(){
        var rs=this.$refs.ti.getContent();
        return rs;
      },
      //设置富文本框的内容
      setTi(v){
        this.$refs.ti.setContent(v);
      },
      getMd(){
        var html=this.$refs.md.getHtml();
        var val =this.$refs.md.getValue();
        return{
          html,
          val
        }
      },
      setMd(v){
        this.$refs.md.setValue(v);
      }
      
  },
    created(){
        this.id=this.$route.params.id;
        console.log(this.id)
        if(this.id){
          this.getproductArticle();
        }
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/myScss";
</style>